import socket
import threading

# 服务器配置
HOST = '127.0.0.1'
PORT = 12345

# 创建服务器套接字
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()

# 存储所有连接的客户端
clients = []
nicknames = []

# 广播消息给所有客户端
def broadcast(message):
    for client in clients:
        try:
            client.send(message)
        except:
            # 若发送失败，移除该客户端
            index = clients.index(client)
            clients.remove(client)
            client.close()
            nickname = nicknames[index]
            nicknames.remove(nickname)
            broadcast(f'{nickname} 离开了聊天！'.encode('utf-8'))

# 处理客户端连接
def handle(client):
    while True:
        try:
            message = client.recv(1024)
            broadcast(message)
        except:
            # 若出现异常，移除该客户端
            index = clients.index(client)
            clients.remove(client)
            client.close()
            nickname = nicknames[index]
            nicknames.remove(nickname)
            broadcast(f'{nickname} 离开了聊天！'.encode('utf-8'))
            break

# 接收客户端连接
def receive():
    while True:
        client, address = server.accept()
        print(f'连接地址: {str(address)}')

        # 接收客户端的昵称
        client.send('NICK'.encode('utf-8'))
        nickname = client.recv(1024).decode('utf-8')
        nicknames.append(nickname)
        clients.append(client)

        print(f'客户端 {nickname} 已连接！')
        broadcast(f'{nickname} 加入了聊天！'.encode('utf-8'))
        client.send('你已连接到服务器！'.encode('utf-8'))

        # 为每个客户端创建一个处理线程
        thread = threading.Thread(target=handle, args=(client,))
        thread.start()

print("服务器正在监听...")
receive()    
